import * as React from "react";
import * as ReactDom from "react-dom";
import classNames from "classnames";

import { BaseProps, BaseHelper } from "../base";

import SpaceWraper from "../spaceWraper";
import Button from "../button";

// 传入组件的属性规约
export type ModalProps = {
  onClick?: React.MouseEventHandler<HTMLElement>;
  title?: string;
  onOk: React.MouseEventHandler<HTMLElement>;
  onCancel: React.MouseEventHandler<HTMLElement>;
  bodyStyle: React.CSSProperties;
  cancelText?: string;
  okText?: string;
  footer?: any;
} & BaseProps;
// TypeScript的无状态组件的写法

class Modal extends React.Component<ModalProps> {
  el: HTMLDivElement;

  constructor(props) {
    super(props);

    this.el = document.createElement("div");
  }

  componentDidMount() {
    const modalRoot = this.props["modalRoot"] || document.body;
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    const modalRoot = this.props["modalRoot"] || document.body;
    modalRoot.removeChild(this.el);
  }

  render() {
    const {
      width,
      height,
      children,

      title,
      onCancel,
      onOk,
      bodyStyle,
      okText = "确定",
      cancelText = "取消",
      footer,
      ...rest
    } = this.props;

    console.log(bodyStyle, "=============bodyStyle=============");

    let _style = BaseHelper.concatStyle(this.props);
    const prefixClass = BaseHelper.getPrefixCls("modal");

    const wrapCls = classNames(
      {
        [`${prefixClass}`]: true,
      },
      this.props.className
    );

    return ReactDom.createPortal(
      <>
        <div className={`${prefixClass}-mask`}></div>
        <div {...rest} className={wrapCls} style={_style}>
          <div className={`${prefixClass}-header`}>
            <div className="left">{title}</div>

            <div className="right">
              <div
                className="right_close_icon"
                onClick={(e) => {
                  onCancel && onCancel(e);
                }}
              ></div>
            </div>
          </div>
          <div className={`${prefixClass}-body`} style={bodyStyle}>
            {children}
          </div>
          <div className={`${prefixClass}-footer`}>
            {footer ? (
              footer
            ) : (
              <SpaceWraper>
                <Button
                  onClick={(e) => {
                    onOk && onOk(e);
                  }}
                >
                  {okText}
                </Button>
                <Button
                  onClick={(e) => {
                    onCancel && onCancel(e);
                  }}
                >
                  {cancelText}
                </Button>
              </SpaceWraper>
            )}
          </div>
        </div>
      </>,
      this.el
    );
  }
}

export default Modal;
